package com.addzero.web.ui.system.hooks

import androidx.compose.foundation.layout.*
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.KeyboardArrowRight
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.Search
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import com.addzero.web.ui.components.ScrollableContainer
import com.addzero.web.ui.system.dynamicroute.RouteMetadata
import com.addzero.web.ui.system.dynamicroute.RouteUtil
import com.addzero.web.ui.system.hooks.side_menu.routeToTree

// 递归过滤树节点的辅助函数
fun filterTreeNodes(nodes: List<RouteMetadata>, query: String): List<RouteMetadata> {
    if (query.isBlank()) {
        return nodes // 如果查询为空，返回原始节点
    }

    val filteredList = mutableListOf<RouteMetadata>()
    for (node in nodes) {
        // 递归过滤子节点
        val filteredChildren = filterTreeNodes(node.children, query)

        // 检查当前节点是否匹配，或者是否有子节点匹配
        val nodeMatches = node.title.contains(query, ignoreCase = true)
        
        if (nodeMatches || filteredChildren.isNotEmpty()) {
            // 如果当前节点匹配，或者有子节点匹配，则保留该节点
            // 如果当前节点不匹配但有子节点匹配，则使用过滤后的子节点列表
            // 如果当前节点匹配，则保留所有原始子节点（或者可以选择也过滤子节点）
            // 这里我们选择：如果父节点匹配，显示所有子节点；如果父节点不匹配但子节点匹配，显示过滤后的子节点
            val childrenToShow = if (nodeMatches) node.children else filteredChildren
            filteredList.add(node.copy(children = childrenToShow))
        }
    }
    return filteredList
}


@Composable
fun SideMenu(
    currentRoute: String,
    onRouteChange: (String) -> Unit,
    userPermissions: List<String> = emptyList(),
) {
    // 获取所有路由组件的元数据，只执行一次
    val allRoutes = remember {
        RouteUtil.scanMetas()
            .filter { it.visible }
            // .filter { route -> userPermissions.containsAll(route.permissions) } // 权限过滤
            .sortedBy { it.order }
    }
    
    // 构建完整的树形结构，只在 allRoutes 变化时执行一次
    val (rootNodes, routeMap) = remember(allRoutes) {
        routeToTree(allRoutes)
    }

    // 搜索状态
    var searchQuery by remember { mutableStateOf("") }

    // 根据搜索查询过滤树，当 searchQuery 或 rootNodes 变化时执行
    val filteredRootNodes = remember(searchQuery, rootNodes) {
        filterTreeNodes(rootNodes, searchQuery)
    }


    Column(modifier = Modifier.width(240.dp).fillMaxHeight()) {
        // 搜索框
        OutlinedTextField(
            value = searchQuery,
            onValueChange = { searchQuery = it },
            modifier = Modifier.fillMaxWidth().padding(8.dp),
            placeholder = { Text("搜索菜单") },
            leadingIcon = { Icon(Icons.Default.Search, contentDescription = "搜索") },
            singleLine = true,
            colors = TextFieldDefaults.colors(
                focusedContainerColor = MaterialTheme.colorScheme.surface,
                unfocusedContainerColor = MaterialTheme.colorScheme.surface,
            )
        )

        // 菜单内容
        ScrollableContainer(
            showScrollbar = true, modifier = Modifier.fillMaxWidth().weight(1f)
        ) {
            Column {
                // 使用过滤后的树节点进行渲染
                TreeSider(
                    data = filteredRootNodes, // 使用过滤后的数据
                    currentId = currentRoute,
                    onNodeSelected = onRouteChange, // 传递原始的导航回调
                    getLabel = { it.title },
                    getChildren = { it.children },
                    content = { node, isSelected, isExpanded -> 
                        val route = node.data
                        val indentation = (node.level * 16).dp

                        NavigationDrawerItem(
                            icon = {
                                route.icon?.let { Icon(it, contentDescription = route.title) }
                            },
                            label = { Text(route.title) },
                            badge = {
                                if (node.children.isNotEmpty()) {
                                    val arrowIcon = if (isExpanded) {
                                        Icons.Default.KeyboardArrowDown
                                    } else {
                                        Icons.AutoMirrored.Filled.KeyboardArrowRight
                                    }
                                    Icon(
                                        imageVector = arrowIcon,
                                        contentDescription = if (isExpanded) "折叠" else "展开",
                                        modifier = Modifier.size(24.dp)
                                    )
                                }
                            },
                            selected = isSelected,
                            onClick = { /* 由 TreeNavigation 处理 */ }, 
                            modifier = Modifier.padding(start = indentation, top = 4.dp, end = 8.dp, bottom = 4.dp),
                            colors = NavigationDrawerItemDefaults.colors(
                                selectedContainerColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.2f),
                                unselectedContainerColor = MaterialTheme.colorScheme.surface
                            )
                        )
                    }
                )
            }
        }
    }
}
